﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Spire.Pdf.Exporting.XPS.Schema;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace FBA.Client.Utils
{
    class NPOIHelper
    {
        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = System.IO.Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                if (workbook == null) { return null; }
                ISheet sheet = workbook.GetSheetAt(0);

                //表头  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    string name = "";
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        try
                        {
                            dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                            name = dr[j].ToString();
                            if (dr[j] != null && dr[j].ToString() != string.Empty)
                            {
                                hasValue = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            // MessageBox.Show(name + ex.Message);
                            return dt;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// Datable导出成Excel
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="file">导出路径(包括文件名与扩展名)</param>
        public static void TableToExcel(DataTable dt, string file)
        {
            IWorkbook workbook;
            string fileExt = System.IO.Path.GetExtension(file).ToLower();
            if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
            if (workbook == null) { return; }
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);


            //表头  
            IRow row = sheet.CreateRow(0);

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
                //设置单元格的样式：水平对齐居中
                //  style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                ICellStyle style = workbook.CreateCellStyle();
                //新建一个字体样式对象
                IFont font = workbook.CreateFont();
                font.FontHeightInPoints = 12;
                //设置字体加粗样式
                font.Boldweight = (short)FontBoldWeight.Bold;
                //使用SetFont方法将字体样式添加到单元格样式中 
                style.SetFont(font);
                //将新的样式赋给单元格
                row.Cells[i].CellStyle = style;

            }
            //数据  
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                row = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                    ICellStyle style = workbook.CreateCellStyle();
                    //新建一个字体样式对象
                    IFont font = workbook.CreateFont();
                    font.FontHeightInPoints = 12;
                    //使用SetFont方法将字体样式添加到单元格样式中 
                    style.SetFont(font);
                    //将新的样式赋给单元格
                    row.Cells[j].CellStyle = style;

                    //单元格宽度自适应（英文/数字）
                    sheet.AutoSizeColumn(j);
                    //单元格宽度自适应（中文）
                    int columnWidth = sheet.GetColumnWidth(j) / 256;
                    for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
                    {
                        IRow currentRow;
                        //当前行未被使用过
                        if (sheet.GetRow(rowNum) == null)
                        {
                            currentRow = sheet.CreateRow(rowNum);
                        }
                        else
                        {
                            currentRow = sheet.GetRow(rowNum);
                        }

                        if (currentRow.GetCell(i) != null)
                        {
                            ICell currentCell = currentRow.GetCell(i);
                            int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                            if (columnWidth < length)
                            {
                                columnWidth = length;
                            }
                        }
                    }
                    sheet.SetColumnWidth(j, columnWidth * 270);
                }


            }
            //转为字节数组  
            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            var buf = stream.ToArray();

            //保存文件夹路径
            string paths = "C:\\Users\\Administrator\\Desktop\\TMS文件";
            //判断文件文件夹是否存在，不存在则创建文件夹
            bool exist = System.IO.Directory.Exists(paths);
            if (exist == false)
            {
                System.IO.Directory.CreateDirectory(paths);//新建一个ShareFile文件夹
            }
            //保存为Excel文件  
            using (FileStream fs = new FileStream(paths + "\\" + file, FileMode.Create, FileAccess.Write))
            {

                fs.Write(buf, 0, buf.Length);
                fs.Flush();
                System.Diagnostics.Process.Start(fs.Name);
            }
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        #region list<T>转datatable
        /// <summary>
        /// list<T>转datatable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }

        #endregion
        #region  datatable转list<T>
        /// <summary>
        /// datatable表转list集合
        /// </summary>
        /// <typeparam name="T">实体类</typeparam>
        /// <param name="dt">datatable表</param>
        /// <param name="rowStart">表的第几行开始计算</param>
        /// <returns>集合List</returns>
        public static List<T> DataTableToList<T>(System.Data.DataTable dt, int rowStart) where T : new()
        {
            List<T> lists = null;
            try
            {
                if (dt.Rows.Count > 0)
                {
                    lists = new List<T>();//定义集合
                    string tempName = string.Empty;
                    for (int i = rowStart; i < dt.Rows.Count; i++)
                    {
                        DataRow myRow = dt.Rows[i];//获取当前行
                        T t = new T();
                        #region 反射入List
                        Type type = t.GetType();
                        foreach (var pi in type.GetProperties())//遍历公共属性
                        {
                            tempName = pi.Name;
                            if (dt.Columns.Contains(tempName))
                            {
                                if (!pi.CanWrite) continue;//该属性不可写，直接跳出
                                if (!pi.PropertyType.IsGenericType)//对属性中有DateTime进行区分对待
                                {
                                    if (pi.Name == "Guid")//对属性为Guid进行特别处理
                                    {
                                        Guid guid = Guid.Empty;
                                        if (!Guid.TryParse(myRow[tempName].ToString(), out guid)) { guid = Guid.NewGuid(); }
                                        pi.SetValue(t, Convert.ChangeType(guid, pi.PropertyType), null);
                                    }
                                    else
                                    {
                                        pi.SetValue(t, Convert.ChangeType(myRow[tempName], pi.PropertyType), null);
                                    }

                                }
                                else
                                {
                                    pi.SetValue(t, Convert.ChangeType(myRow[tempName], Nullable.GetUnderlyingType(pi.PropertyType)), null);
                                }

                            }
                            #endregion
                        }
                        lists.Add(t);
                    }
                }
                return lists;
            }
            catch (Exception)
            {
                MessageBox.Show(Language.Get("Lang.IncorrectFormat"));
                return lists;
            }
        }

        #endregion

    }
}
